import java.util.*;

public class Solution508 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max=0;

    public int[] findFrequentTreeSum(TreeNode root) {
        Map<Integer,Integer> map=new HashMap<>();
        dfs(root,map);
        List<Integer> list=new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue()==max){
                list.add(entry.getKey());
            }
        }
        int[] ans=new int[list.size()];
        for (int i=0;i<list.size();i++){
            ans[i]=list.get(i);
        }
        return ans;
    }

    private int dfs(TreeNode root, Map<Integer, Integer> map) {
        if (root==null){
            return 0;
        }
        int count=root.val;
        count+=dfs(root.left,map);
        count+=dfs(root.right,map);
        map.put(count,map.getOrDefault(count,0)+1);
        max=Math.max(max,map.get(count));
        return count;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution508().findFrequentTreeSum(new TreeNode(5, new TreeNode(2), new TreeNode(-3)))));
    }
}
